﻿using System;
using System.Data.Entity.Design;
using System.Data.Metadata.Edm;
using System.IO;

namespace Sylva.AppML.DatabaseSchema
{
    /// <summary>
    /// This class is used for manage database schema.
    /// </summary>
    public partial class SchemaManager
    {
        public string ConnectionString { get; set; }

        public string SchemaFile { get; set; }

        /// <summary>
        /// Generates an entity data model from a data source.
        /// </summary>
        /// <param name="options">Options for generating entity data model.</param>
        /// <returns>The entity container</returns>
        public static EntityContainer GenerateEdm(GenerateEdmOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            // Delete old generated files
            if (Directory.Exists(options.GeneratedPath))
            {
                Directory.Delete(options.GeneratedPath, true);
            }

            // Create the folder
            Directory.CreateDirectory(options.GeneratedPath);

            // Generating...
            EntityStoreSchemaGenerator generator = new EntityStoreSchemaGenerator(options.ProviderInvariantName,
                options.ConnectionString,
                options.Namespace);
            generator.GenerateStoreMetadata();
            generator.WriteStoreSchema(options.StoreSchemaFileName);

            return generator.EntityContainer;
        }
    }
}
